package zhoug.common.utils;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;

import zhoug.common.interfaces.Callback2;
import zhoug.logging.Logger;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 开关debug配置
 * @Author 35574
 * @Date 2020/4/30
 * @Description
 */
public class DebugModelUtils {
    private static final String TAG = ">>>DebugModelUtils";
    private long startTime = 0;
    private volatile int counter = 0;
    private static final int during = 4000;
    private Context appContext;
    private Callback2<Boolean> callback;
    private int maxCounter=8;

    public DebugModelUtils(Context appContext) {
        if (appContext instanceof Application) {
            this.appContext = appContext;
        } else {
            this.appContext = appContext.getApplicationContext();
        }
    }

    public void setCallback(Callback2<Boolean> callback) {
        this.callback = callback;
    }

    public static boolean isOpenDebugModel() {
        return _getDefSP().getBoolean("isOpenDebug", false);
    }

    private static void setOpenDebugModel(boolean openDebugModel) {
        SharedPreferences sharedPreferences = _getDefSP();
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putBoolean("isOpenDebug", openDebugModel);
        edit.apply();
    }

    /**
     * 开关显示服务器配置
     */
    public void switchDebugModel() {
        if (counter == 0) {
            startTime = System.currentTimeMillis();
            counter++;
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    counter = 0;
                }
            }, during);
        } else if (counter == maxCounter) {
            long time = System.currentTimeMillis() - startTime;
            if (time < during) {
                boolean open_debug = !isOpenDebugModel();
                setOpenDebugModel(open_debug);

                ToastUtils.toastShort(appContext, open_debug ? "开启开发者模式" : "关闭开发者模式");
                if (callback != null) {
                    callback.onResult(open_debug);
                }
            }
            counter = 0;
        } else {
            counter++;
        }
        Logger.d(TAG, "openDebug: counter=" + counter);
    }

    private static SharedPreferences _getDefSP() {
        return SpUtils.getDefaultSharedPreferences();
    }


}
